package com.jeecg.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.demo.controller.ZhaobiaopmjyBaomController;
import com.jeecg.demo.entity.*;
import com.jeecg.demo.service.*;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("bzjOperatorService")
@Transactional
public class BzjOperatorServiceImpl extends CommonServiceImpl implements BzjOperatorServiceI {

	private static final Logger logger = LoggerFactory.getLogger(BzjOperatorServiceImpl.class);

	@Autowired
	BzjConfigServiceI bzjConfigServiceI;
	@Autowired
	PostorderServiceI postorderServiceI;
	@Autowired
	private SettlementServiceI settlementServiceI;
	@Autowired
	private SystemService systemService;
	@Autowired
	private TraderServiceI traderServiceI;

	
 	public BzjOperatorLogEntity operatorForBaomByConfig(ZhaobiaopmjyBaomEntity bm) {

 		String result = "0";
		BzjOperatorLogEntity logEntity = new BzjOperatorLogEntity();
		List<PostorderEntity> poList = postorderServiceI.findByProperty(PostorderEntity.class, "pocode", bm.getPocode());

		logEntity.setCreatetime(new Date());
		logEntity.setTraderid(String.valueOf(bm.getTraderid()));
		logEntity.setPocode(bm.getPocode());
		logEntity.setMark("-1");
		logEntity.setFlag("-1");


		if (poList.size() > 0) {

			PostorderEntity po = poList.get(0);
			List<BzjConfigEntity> configList = bzjConfigServiceI.findHql("from BzjConfigEntity c where c.modeid = ? and c.modedirectory = ? ", String.valueOf(po.getTrademodeid()), po.getDirection());
			if (configList.size() > 0) {
				BzjConfigEntity bzj = configList.get(0);
				logEntity.setFormulas(JSONObject.toJSONString(bzj).toString());
				if (bzj.getEnable() == 1) {
					if (bzj.getMeans().equals("0")) {
						if (bzj.getTarget().equals("1") || bzj.getTarget().equals("2")) {
							result = this.formatResult(bzj.getAmount());
							logEntity.setMark("1");
							logEntity.setFlag("0");
						}
					}else if (bzj.getMeans().equals("1")) {
						if (bzj.getTarget().equals("1") || bzj.getTarget().equals("2")) {
							double amount = po.getPoquantity().doubleValue() * po.getPoprice().doubleValue() * bzj.getRate();
							result = this.formatResult(amount);
							logEntity.setMark("1");
							logEntity.setFlag("0");
						}
					}
				}else {

				}

				logEntity.setResult(result);
			}
		}else {

		}
		//this.saveOrUpdate(logEntity);
        //return result;
		return logEntity;
	}

	public String operatorForPostorderByConfig(PostorderEntity po) {

 		String res = "";
		String result = "0";
		BzjOperatorLogEntity logEntity = new BzjOperatorLogEntity();
		List<BzjConfigEntity> configList = bzjConfigServiceI.findHql("from BzjConfigEntity c where c.modeid = ? and c.modedirectory = ? ", String.valueOf(po.getTrademodeid()), po.getDirection());

		logEntity.setMark("-1");
		logEntity.setFlag("-1");
		logEntity.setCreatetime(new Date());
		logEntity.setTraderid(String.valueOf(po.getPotraderid()));
		logEntity.setPocode(po.getPocode());

		if (configList.size() > 0) {
			BzjConfigEntity bzj = configList.get(0);
			logEntity.setFormulas(JSONObject.toJSONString(bzj).toString());
			if (bzj.getEnable() == 1) {
				if (bzj.getMeans().equals("0")) {
					if (bzj.getTarget().equals("0") || bzj.getTarget().equals("2")) {
						result = this.formatResult(bzj.getAmount());
						res = this.operatorForPostorder(po,result);
						logEntity.setMark("0");
						logEntity.setFlag("0");
					}
				}else if (bzj.getMeans().equals("1")) {
					if (bzj.getTarget().equals("0") || bzj.getTarget().equals("2")) {
						double amount = po.getPoquantity().doubleValue() * po.getPoprice().doubleValue() * bzj.getRate();
						result = this.formatResult(amount);
						res = this.operatorForPostorder(po,result);
						logEntity.setMark("0");
						logEntity.setFlag("0");
					}
				}
			}else {

			}

			logEntity.setResult(result);
			if (res.equals("success")) {
				this.saveOrUpdate(logEntity);
			}
		}
		return res;
	}

	public boolean isExistBzjData (String pocode, String traderid,String mark, String flag) {
 		boolean ret = false;
		//Long count = this.getCountForJdbcParam("select * from BZJ_OPERATOR_LOG l where l.pocode = ? and l.traderid = ?", pocode, traderid);
		List<BzjOperatorLogEntity> list = this.findHql("from BzjOperatorLogEntity l where l.pocode = ? and l.traderid = ? and l.mark = ? and l.flag = ?", pocode, traderid,mark, flag);
		if (list.size() > 0) {
			ret = true;
		}
		return ret;
	}


	private String formatResult (Double d) {
 		 DecimalFormat decimalFormat = new DecimalFormat("0"); // 设定格式，保留4位小数
		  String str = decimalFormat.format(d);
	     return str;
 	}


 	private String operatorForPostorder(PostorderEntity po, String tranferMoeny) {

 		String res = "";
		Map<String, Object> map = new HashMap();

		TraderEntity trader = traderServiceI.get(TraderEntity.class,po.getPotraderid());
		String tradecode = trader.getTradecode();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String time = sdf.format(date);
		String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 15);
		Integer subectId = 315;
		Integer type = 0;
		String demo = "挂单保证金";
		map.put("firmId", tradecode);
		map.put("subectId", subectId);

		map.put("tranferMoeny", tranferMoeny);
		map.put("transferTime", time);
		map.put("sertalNo", uuid);
		map.put("type", type);
		map.put("demo", demo);
		String params = JSON.toJSONString(map);
		String methond = "freezeDeposit";
		String result = null;
		try {
			logger.info("发送挂单冻结信息 ：" + params);
			result = settlementServiceI.doSettlement(params, methond);
			if ("success".equals(result)) {
				FreezeDepositEntity freezeDepositEntity = new FreezeDepositEntity();
				freezeDepositEntity.setTraderCode(tradecode);
				freezeDepositEntity.setSubectId(subectId);
				freezeDepositEntity.setTranferMoeny(tranferMoeny);
				freezeDepositEntity.setTransferTime(time);
				freezeDepositEntity.setSertalNo(uuid);
				freezeDepositEntity.setType(type);
				freezeDepositEntity.setDemo(demo);
				freezeDepositEntity.setStatus(1);
				freezeDepositEntity.setPocode(po.getPocode());
				systemService.save(freezeDepositEntity);
			}else {

			}
			res = result;
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			res = "系统错误";

		}finally {
			return res;
		}

	}
 	
}